package org.metamodelos2.modelo.insercion;

import java.net.UnknownHostException;
import java.util.Calendar;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class InsertarMongoID {

	public InsertarMongoID(){
		Long t1=Calendar.getInstance().getTimeInMillis();
		Mongo m=null;
		try {
			m = new Mongo("192.168.0.14",27017);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
		Long t2=Calendar.getInstance().getTimeInMillis();
		DB db=m.getDB("test");
		DBCollection coll=db.getCollection("coleccionPrueba3");
		DBCollection collConsecutivo=db.getCollection("consecutivo");
		Long t3=Calendar.getInstance().getTimeInMillis();
		for(Long i=0L;i<100;i++){
			
			BasicDBObject dbo=new BasicDBObject();
			dbo.put("_id", obtenerConsecutivo(collConsecutivo));
			dbo.put("long", i);
			dbo.put("string", "12345678901234567890");
			dbo.put("date",Calendar.getInstance().getTime());
			dbo.put("double", 1.0001);
			
			coll.insert(dbo);
		}
		Long t4=Calendar.getInstance().getTimeInMillis();
		m.close();
		Long t5=Calendar.getInstance().getTimeInMillis();
		System.out.println("conexion: "+(t2-t1));
		System.out.println("obtener bd y coleccion: "+(t3-t2));
		System.out.println("insertar 100 registros: "+(t4-t3));
		System.out.println("cierre: "+(t5-t4));
	}
	
	public static void main(String[] args) {
		new InsertarMongoID();
	}
	
	
	public Long obtenerConsecutivo(DBCollection coleccion){
		BasicDBObject query=new BasicDBObject();
		query.put("_id", "prueba3");
		DBCursor cur=coleccion.find(query);
		Double id=0.0;
		if(cur.hasNext()){
			DBObject con=cur.next();
			id=(Double) con.get("consecutivo");
			query.put("consecutivo", id+1);
			coleccion.save(query);
		}
		return id.longValue();
	}
	
}
